import type { DataColorType, DataFormField } from '../DataField'
import { hasAnyAuth } from '@/utils/authUtil'

export interface DataAction {
  label: string | ((data: any) => string)
  type?: DataColorType | ((data: any) => DataColorType)
  authCode?: string
  confirm?: string | ((data: any) => string)
  show?: (data: any) => boolean
  click?: (data: any, index?: number) => any
  success?: (data: any, index?: number) => any
  message?: ((data: any) => any) | boolean | string
}

export interface DataFormDrawerProp<T> {
  fields?: DataFormField[]
  cols?: 1 | 2 | 3 | 4
  size?: 'small' | 'default' | 'large'
  width?: string | number
  disabled?: boolean
  title?: string
  submit?: (data: T) => Promise<any>
}

export interface DataFormProp<T extends Record<string, any>> {
  fields?: DataFormField[]
  submit?: (data: T) => Promise<any>
  disabled?: boolean
  cols?: 1 | 2 | 3 | 4
  size?: 'small' | 'default' | 'large'
}

export async function doDataAction(data: any, action: DataAction, index?: number) {
  const label = typeof action.label === 'function' ? action.label(data) : action.label
  if (action.authCode !== undefined && !hasAnyAuth(action.authCode)) {
    ElMessage.error(`无权限${label}`)
    return
  }
  if (action.confirm) {
    const confirmMessage = (typeof action.confirm === 'function') ? action.confirm(data) : action.confirm
    const result = await ElMessageBox.confirm(
      confirmMessage,
      '请确认？',
      { type: 'warning', draggable: true },
    ).catch(() => 'cancel')
    if (result === 'cancel') {
      return
    }
  }
  if (action.click) {
    const result = await action.click(data, index)
    if (action.success) {
      await action.success(result, index)
    }
    if (action.message !== undefined) {
      if (typeof action.message === 'function') {
        ElMessage.success(action.message(result))
      }
      if (typeof action.message === 'boolean' && action.message === true) {
        ElMessage.success(`${label}成功`)
      }
      if (typeof action.message === 'string') {
        ElMessage.success(action.message)
      }
    }
  }
}
